import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Transaction;

import model.Employee;
import model.EmployeeLanguage;
import model.Language;

public class EmployeeController extends Controller
{
	private static final long	serialVersionUID	= -8160003372674934722L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		super.doGet(request, response);
	}

	public void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		ServletContext sc = getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher("/main");
		rd.forward(request, response);
	}

	public void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String html = getViewHtml("employee", "index");
		String list_html = getEmployeeList();
		html = html.replaceAll("\\{employee_list\\}", list_html);
		renderView(html, response);
	}

	public String getEmployeeList()
	{
		String list = "";
		list += "<tbody>";

		for (int category = 1; category <= 3; category++)
		{
			ArrayList<Employee> employees = Employee.getAllEmployeeByNameASC(getSession(), category);
			list += "<tr id=\"text\"><td style=\"background-color: #3fa9cc;\" colspan=\"11\">" + Employee.getCategoryName(category) + "</td></tr>";
			for (Employee employee : employees)
			{
				list += getEmployeeListRow(employee, false);
			}
		}
		list += "</tbody>";
		return list;
	}

	public String getEmployeeListRow(Employee employee, boolean ajax)
	{
		String row = "";
		if ( !ajax )
			row += "<tr id=\"text\" employee_row=\"" + employee.getId() + "\">";
		row += "<td>" + employee.getName() + "</td>";
		row += "<td>" + employee.getGenderString() + "</td>";
		row += "<td>" + employee.getAge() + "</td>";
		row += "<td>" + employee.getRank() + "</td>";
		row += "<td>";
		String tmp = "";
		for (EmployeeLanguage employeeLanguage : EmployeeLanguage.getEmployeeLanguagesByEmployee(getSession(), employee))
			tmp += employeeLanguage.getLanguage().getLanguage() + ", ";
		row += tmp.substring(0, tmp.length() != 0 ? tmp.length() - 2 : tmp.length());
		row += "</td>";
		row += "<td>" + employee.getWillFlyTimeOnThisMonth(false, null) + "</td>";
		row += "<td>" + employee.getFlyTimeTotal() + "</td>";
		row += "<td>" + StaticMethods.getFormattedDateForDate(employee.getPassportExpiredDate()) + "</td>";
		row += "<td>" + employee.getPassportNumber() + "</td>";
		row += "<td><img style=\"cursor: pointer\" src=\"{path}images/edit.png\" id=\"editemployee\" employeeid=\"" + employee.getId() + "\"/></td>";
		row += "<td><img style=\"cursor: pointer\" src=\"{path}images/delete.png\" id=\"deleteemployee\" employeeid=\"" + employee.getId() + "\"/></td>";
		if ( !ajax )
			row += "</tr>";
		row = row.replaceAll("\\{path\\}", StaticMethods.PATH);
		return row;
	}

	public void deleteEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		long employeeId = Long.parseLong(request.getParameter("employeeid"));
		Employee employee = (Employee) getObjectByPk(Employee.class, employeeId);
		try
		{
			Transaction transaction = getSession().beginTransaction();
			getSession().delete(employee);
			transaction.commit();
			renderView("1", response);
		}
		catch (Exception e)
		{
			renderView("0", response);
		}
	}

	public void dialogEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String dialog_html = getViewHtml("employee", "dialog");
		boolean flag = request.getParameter("employeeid") == null ? false : true;
		long employeeId = flag ? Long.parseLong(request.getParameter("employeeid")) : -1;
		Employee employee = flag ? (Employee) getObjectByPk(Employee.class, employeeId) : null;

		dialog_html = dialog_html.replaceAll("\\{employee\\_id\\}", flag ? employee.getId() + "" : "");
		dialog_html = dialog_html.replaceAll("\\{\\_VALUE\\_NAME\\_\\}", flag ? employee.getName() : "");
		dialog_html = dialog_html.replaceAll("\\{gender\\_male\\}", flag ? (employee.isGender() ? "selected=\"selected\"" : "") : "");
		dialog_html = dialog_html.replaceAll("\\{gender\\_female\\}", flag ? (!employee.isGender() ? "selected=\"selected\"" : "") : "");

		dialog_html = dialog_html.replaceAll("\\{cat\\_senior\\}", flag ? (employee.getCategory() == Employee.EMPLOYEE_CATEGORY_SENIOR_STEWARDS ? "selected=\"selected\"" : "") : "");
		dialog_html = dialog_html.replaceAll("\\{cat\\_assist\\}", flag ? (employee.getCategory() == Employee.EMPLOYEE_CATEGORY_SENIOR_ASSIST_STEWARDS ? "selected=\"selected\"" : "") : "");
		dialog_html = dialog_html.replaceAll("\\{cat\\_stewardess\\}", flag ? (employee.getCategory() == Employee.EMPLOYEE_CATEGORY_STEWARDS ? "selected=\"selected\"" : "") : "");

		dialog_html = dialog_html.replaceAll("\\{\\_VALUE\\_AGE\\_\\}", flag ? employee.getAge() + "" : "");
		dialog_html = dialog_html.replaceAll("\\{\\_VALUE\\_RANK\\_\\}", flag ? employee.getRank() + "" : "");
		dialog_html = dialog_html.replaceAll("\\{language\\_list\\}", getLanguageList(employee));
		dialog_html = dialog_html.replaceAll("\\{\\_VALUE\\_MONTH\\_FLIGHT\\_\\}", flag ? employee.getWillFlyTimeOnThisMonth(false, null) + "" : "");
		dialog_html = dialog_html.replaceAll("\\{\\_VALUE\\_TOTAL\\_FLIGHT\\_\\}", flag ? employee.getFlyTimeTotal() + "" : "");
		dialog_html = dialog_html.replaceAll("\\{\\_VALUE\\_PASS\\_EXDATE\\_\\}", flag ? StaticMethods.getFormattedDateForDate(employee.getPassportExpiredDate()) + "" : "");
		dialog_html = dialog_html.replaceAll("\\{\\_VALUE\\_PASS\\_NO\\_\\}", flag ? employee.getPassportNumber() + "" : "");
		renderView(dialog_html, response);
	}

	@SuppressWarnings({ "unchecked", "static-access" })
	public String getLanguageList(Employee employee)
	{
		String list_html = "";
		ArrayList<Language> languages = (ArrayList<Language>) getAllObjects(Language.class);
		ArrayList<Long> employeeCurrentLanguagesId = new ArrayList<Long>();
		if ( employee != null )
			employeeCurrentLanguagesId = employee.getCurrentLanguagesId(getSession(), employee);
		for (Language language : languages)
		{
			boolean be = employeeCurrentLanguagesId.contains(language.getId());
			list_html += "<option " + (be ? "selected=\"selected\"" : "") + " value=" + language.getId() + ">" + language.getLanguage() + "</option>";
		}
		return list_html;
	}

	@SuppressWarnings("deprecation")
	public void saveEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		try
		{
			Transaction transaction = getSession().beginTransaction();
			boolean flag = (request.getParameter("employeeid") == null) ? false : true;
			long employeeId = flag ? Long.parseLong(request.getParameter("employeeid")) : -1;
			Employee employee = flag ? (Employee) getObjectByPk(Employee.class, employeeId) : (new Employee());

			employee.setName(getParameter("name"));
			boolean gender = getParameter("gender").equals("0") ? false : true;
			employee.setGender(gender);
			employee.setAge(Integer.parseInt(getParameter("age")));
			employee.setRank(Integer.parseInt(getParameter("rank")));
			employee.setFlyTimeTotal(Float.parseFloat(getParameter("total")));
			employee.setPassportExpiredDate(new Date(getParameter("passexdate")));
			employee.setPassportNumber(getParameter("passno"));
			employee.setCategory(Integer.parseInt(getParameter("category")));
			if ( flag )
			{
				getSession().update(employee);
			}
			else
			{
				getSession().save(employee);
			}

			ArrayList<Long> employeeCurrentLanguagesId = employee.getCurrentLanguagesId();

			int lan_count = 0;
			String lan_id_str = "";
			while ((lan_id_str = request.getParameter("lan" + lan_count)) != null)
			{
				long lang_id = Long.parseLong(lan_id_str);
				if ( !employeeCurrentLanguagesId.contains(lang_id) )
				{
					Language language = (Language) getObjectByPk(Language.class, lang_id);

					EmployeeLanguage employeeLanguage = new EmployeeLanguage();
					employeeLanguage.setEmployee(employee);
					employeeLanguage.setLanguage(language);
					getSession().save(employeeLanguage);
				}
				else
				{
					employeeCurrentLanguagesId.remove(lang_id);
				}
				lan_count++;
			}
			for (long l : employeeCurrentLanguagesId)
			{
				Language language = (Language) getObjectByPk(Language.class, l);
				EmployeeLanguage employeeLanguage = EmployeeLanguage.getEmployeeLanguage(getSession(), employee, language);
				getSession().delete(employeeLanguage);
			}
			transaction.commit();

			employee = (Employee) getObjectByPk(Employee.class, employeeId);
			if ( flag )
			{
				renderView(getEmployeeListRow(employee, true), response);
			}
			else
			{
				renderView(getEmployeeList(), response);
			}
		}
		catch (Exception exception)
		{
			renderView("0", response);
			exception.printStackTrace();
		}
	}
}